//定制请求的实例

//导入axios  npm install axios
import axios from 'axios';

import { ElMessage } from 'element-plus'
//定义一个变量,记录公共的前缀  ,  baseURL
//const baseURL = 'http://localhost:8080';
const baseURL = '/api';
const instance = axios.create({baseURL})

import { useTokenStore } from '@/stores/token';

//请求请求拦截器
instance.interceptors.request.use(
    (config)=>{
        const tokenStore = useTokenStore();
        //在请求头中添加token
        if(tokenStore.token){
            config.headers.Authorization = tokenStore.token;
        }
        return config;
    },
    (err) =>{
        return Promise.reject(err);
    }
)

import router from '@/router'

//添加响应拦截器
instance.interceptors.response.use(
    result=>{
        //判断业务状态码
        if(result.data.code === 0){
            return result.data;
        }
        
        //alert(result.data.msg ? result.data.msg : '服务异常')
        ElMessage({
            message:result.data.message ? result.data.message : '服务异常',
            type:'error'
        })
        return Promise.reject(result.data);
    },
    err=>{
        //alert('服务异常');
        if(err.response.status === 401){
            ElMessage({
                message:'请先登录',
                type:'error'
            })

            router.push('/login'); 

        }else{
            ElMessage({
                message:'服务异常',
                type:'error'
            })
            return Promise.reject(err);//异步的状态转化成失败的状态
        }

    }
)

export default instance;